﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BLL.Base;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;

namespace BLL.Basis
{
    public class BanGunBLL : PubMethod
    {
        Commands cmd;
        LoginInfo userLogin;
        List<OperateModel> operList;
        OperateModel oper;
        ReturnResult rsl;
        public BanGunBLL()
        {
            cmd = new Commands();
            userLogin = new LoginInfo();
        }
        /// <summary>
        /// 版辊数据显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="typesCode"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getBanGunList(string pageIndex, string pageSize, ref string pageCount, string condition, bool inHouse = false)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("isdel=0 and baseCode='"+ userLogin.UserInfo().baseCode +"'");
                if (inHouse)
                {
                    sb.Append(" and bstatus='inhouse'");
                }
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "typeCode")
                            {
                                sb.Append(obj.Name + "='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }
                          
                        }
                    }
                }
                rsl.Data = cmd.PageList<ViewBanGun>("V_BanGun_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 样板数据显示
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <param name="inHouse"></param>
        /// <returns></returns>
        public ReturnResult getYangBanList(string pageIndex, string pageSize, ref string pageCount, string condition, bool inHouse = false)
        {
            rsl = new ReturnResult();
            try
            {
                if (string.IsNullOrWhiteSpace(pageIndex))
                {
                    pageIndex = "1";
                }
                if (string.IsNullOrWhiteSpace(pageSize))
                {
                    pageSize = Tools.ConfigReader.Reader["PageSize"];
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("isdel=0 ");
                if (!string.IsNullOrWhiteSpace(condition))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(condition);
                    foreach (JProperty obj in json.Properties())
                    {
                        if (!string.IsNullOrWhiteSpace(obj.Value.ToString()))
                        {
                            if (!string.IsNullOrWhiteSpace(sb.ToString()))
                            {
                                sb.Append(" and ");
                            }
                            if (obj.Name == "typeCode")
                            {
                                sb.Append(obj.Name + "='" + obj.Value.ToString() + "' ");
                            }
                            else
                            {
                                sb.Append(obj.Name + " like '%" + obj.Value.ToString() + "%' ");
                            }

                        }
                    }
                }
                rsl.Data = cmd.PageList<ViewYangBan>("V_YangBan_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                rsl.Result = true;

            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
     

        /// <summary>
        /// 版辊信息
        /// </summary>
        /// <param name="pCode"></param>
        /// <returns></returns>
        public ReturnResult getBanGunInfoByCode(string pCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BanGun_Info where id='" + pCode + "'");
                var table = cmd.GetDataTable(sb.ToString());

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 样板信息
        /// </summary>
        /// <param name="bCode"></param>
        /// <returns></returns>
        public ReturnResult getYangBanInfoByCode(string bCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_YangBan_info where id='" + bCode + "'");
                var table = cmd.GetDataTable(sb.ToString());

                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 样板信息更新
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public ReturnResult UpdateYangBan(string jsonStr)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    rsl.Message = "提交数据为空";
                    return rsl;
                }

                operList = new List<OperateModel>();
                DbYangBan yangban = JsonConvert.DeserializeObject<DbYangBan>(jsonStr);
                sb.Append("select * from fun_YangBan_info where isdel=0 ");
                sb.Append(" and id='" + yangban.id + "'");
                var qTable = cmd.GetDataTable(sb.ToString());
                sb.Clear();
                sb.Append("select id from fun_YangBanProduct_info where ");
                sb.Append("yCode='"+ yangban.yCode +"'");
                var ypTable = cmd.GetDataTable(sb.ToString());
                oper = new OperateModel();
                if (yangban.id == null || yangban.id == 0)
                {
                    #region 添加操作
                    if (qTable.Rows.Count > 0)
                    {
                        rsl.Message = "编码已存在"; return rsl;
                    }
                    yangban.createtime = getNow();
                    yangban.createuser = userLogin.UserInfo().userCode;
                    yangban.isdel = 0;
                    yangban.yStatus = "ybin";//默认状态为在库     
                    oper.Types = OperateModel.OperateType.Add;
                    #endregion
                }
                else
                {
                    #region 修改
                    oper.Types = OperateModel.OperateType.Edit;
                    oper.Conditions = "id";
                    #endregion
                }
                yangban.proCount = ypTable.Rows.Count.ToString();
                oper.Data = yangban;
                operList.Add(oper);
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除样板
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelYangBan(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();

                var warranty = new DbYangBan
                {
                    //delDate = getNow(),
                    //delUser = userLogin.UserInfo().userCode,
                    id = int.Parse(dataId),
                    isdel = 1,
                };

                oper = new OperateModel();
                oper.Data = warranty;
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "id";
                operList.Add(oper);

                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #region 通用树结构
        /// <summary>
        /// 通用树结构
        /// </summary>
        /// <param name="trType">类型编码</param>
        /// <returns></returns>
        public ReturnResult TreeNavigation(string trType)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonTree_info ");
                sb.Append(" where isdel=0  and trType='"+ trType +"'");
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息


                List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
                #region 构建数据
                var fMenu = table.Select("parentCode='0'");//获取所有父级菜单
                for (int i = 0; i < fMenu.Length; i++)
                {
                    var fdic = new Dictionary<string, object>();
                    fdic["title"] = fMenu[i]["trName"].ToString();
                    fdic["id"] = fMenu[i]["trCode"].ToString();
                    fdic["spread"] = "true";
                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.ChildUrl(table, fMenu[i]["trCode"].ToString(), ref  cList);
                    fdic["children"] = cList;
                    #endregion
                    menuList.Add(fdic);
                }
                #endregion
                rsl.Data = menuList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="cCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void ChildUrl(DataTable table, string cCode, ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentCode='" + cCode + "'");
            if (dr.Length > 0)
            {
                for (int x = 0; x < dr.Length; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = dr[x]["trName"].ToString();
                    cdic["id"] = dr[x]["trCode"].ToString();
                    ChildUrl(table, dr[x]["trCode"].ToString(), ref tempList);
                    cdic["spread"] = "true";
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
        #endregion
       
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="datas">数据</param>
        /// <param name="operType">操作类型(0编辑 1添加)</param>
        /// <param name="dType">数据类型</param>
        /// <returns></returns>
        public ReturnResult SaveTypeData(string datas,string operType,string dType)
        {
            rsl = new ReturnResult();
            try
            {
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbCommomTree cTree = new DbCommomTree();
                StringBuilder sb = new StringBuilder();
                cTree.trName = json["trName"].ToString();
                if (operType == "1")
                {
                    #region 添加操作
                    cTree.isdel = 0;
                    sb.Append("select top 1 * from fun_CommonTree_info where parentCode='" + json["trCode"] + "' ");
                    sb.Append(" order by id desc");
                    var table = cmd.GetDataTable(sb.ToString());
                    string newCode = "";
                    if (table.Rows.Count < 1)
                    {
                        newCode = json["trCode"].ToString() + "001";
                    }
                    else
                    {
                        newCode = (int.Parse(table.Rows[0]["trCode"].ToString()) + 1).ToString();
                    }
                    cTree.trCode = newCode;
                    cTree.trType = dType;
                    cTree.parentCode = json["trCode"].ToString();
                    cTree.createtime = getNow();
                    cTree.createuser = userLogin.UserInfo().userCode;
                    rsl = cmd.Add(cTree);
                    #endregion
                }
                else
                {
                    cTree.trCode = json["trCode"].ToString();
                    oper = new OperateModel();
                    oper.Conditions = "trCode";
                    oper.Data = cTree;
                    oper.Types = OperateModel.OperateType.Edit;
                    rsl = cmd.Edit(oper);
                }
               
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 删除信息(通用数据树)
       /// </summary>
       /// <param name="trCode"></param>
       /// <returns></returns>
        public ReturnResult DelTypeData(string trCode)
        {
            rsl = new ReturnResult();
            try
            {
                DbCommomTree tr = new DbCommomTree();
                tr.trCode = trCode;
                tr.isdel = 1;
                tr.delDate = DateTime.Now.ToString();
                tr.deluser = userLogin.UserInfo().userCode;
                oper = new OperateModel();
                oper.Data = tr;
                oper.Conditions = "trCode";
                oper.Types = OperateModel.OperateType.Edit;
                rsl = cmd.Edit(oper);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 更改版辊状态
        /// </summary>
        /// <param name="datas">数据信息</param>
        /// <returns></returns>
        public ReturnResult SetBanGunStatus(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbBanGun ban;
                var arr = json["pCodes"].ToString().Split(',');
                foreach (string str in arr)
                {
                    if (!string.IsNullOrWhiteSpace(str))
                    {
                        ban = new DbBanGun();
                        ban.bStatus = json["doType"].ToString();
                        ban.pCode = str;
                        if (json["doType"].ToString() == "repHouse")
                        {
                            if (string.IsNullOrWhiteSpace(json["zhishu"].ToString()))
                            {
                                rsl.Message = "维修支数不能为空";
                                return rsl;
                            }
                            ban.banzhi = json["zhishu"].ToString();
                        }
                        oper = new OperateModel();
                        oper.Data = ban;
                        oper.Conditions = "pCode";
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);

                        #region 添加记录信息
                        DbBanGunRecords re = new DbBanGunRecords();
                        re.transport = json["transport"].ToString();
                        re.doType = json["doType"].ToString();
                        re.money = json["money"].ToString();
                        re.zhishu = json["zhishu"].ToString();
                        re.createtime = getNow();
                        re.dType = "BG";
                        re.pCode = str;
                        re.memo = json["memo"].ToString();
                        re.createuser = userLogin.UserInfo().userCode;
                        re.usCode = json["usersCode"].ToString();
                        oper = new OperateModel();
                        oper.Data = re;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 版辊记录信息
        /// </summary>
        /// <param name="pCode">版辊编码</param>
        /// <returns></returns>
        public ReturnResult GetBanGunRecordsByCode(string pCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_BanGunRecords_info where pCode='"+ pCode +"'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
       /// <summary>
       /// 样版存货信息保存
       /// </summary>
       /// <param name="proCodes">存货集合</param>
       /// <param name="yCode">样版编码</param>
       /// <returns></returns>
        public ReturnResult SaveYangBanProduct(string proCodes,string yCode)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                var arr = proCodes.Split(',');
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_YangBanProduct_info where yCode='" + yCode + "'");
                var ypTale = cmd.GetDataTable(sb.ToString());
                DbYangBanProduct ypro;
                foreach (string str in arr)
                {
                    var dr = ypTale.Select("proCode='" + str + "'");
                    if (dr.Length > 0)
                    {
                        rsl.Message = string.Format("存货已选择：{0}", str);
                        return rsl;
                    }

                    ypro = new DbYangBanProduct();
                    ypro.createtime = getNow();
                    ypro.createuser = userLogin.UserInfo().userCode;
                    ypro.proCode = str;
                    ypro.status = "N";
                    ypro.yCode = yCode;
                    oper = new OperateModel();
                    oper.Data = ypro;
                    oper.Types = OperateModel.OperateType.Add;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
              
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取样版存货信息
        /// </summary>
        /// <param name="yCode"></param>
        /// <param name="isAll"></param>
        /// <returns></returns>
        public ReturnResult getYangBanProducts(string yCode,bool isAll=false)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_YangBanProducts_info ");
                sb.Append(" where yCode='" + yCode + "' and baseCode='"+ userLogin.UserInfo().baseCode +"'");
                if (!isAll)
                {
                    sb.Append(" and status='Y'");
                }
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Data = cmd.TableToDictionary(table);
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 删除样版存货信息
        /// </summary>
        /// <param name="dataId"></param>
        /// <returns></returns>
        public ReturnResult DelYangBanProduct(string dataId)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("delete from fun_YangBanProduct_info where id="+dataId);
                rsl = cmd.UpdateSql(sb.ToString());
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 更改样版状态
        /// </summary>
        /// <param name="datas">数据信息</param>
        /// <returns></returns>
        public ReturnResult YangBanStatus(string datas)
        {
            rsl = new ReturnResult();
            try
            {
                operList = new List<OperateModel>();
                var json = JsonConvert.DeserializeObject<JObject>(datas);
                DbYangBan ban;
                var arr = json["yCodes"].ToString().Split(',');
                foreach (string str in arr)
                {
                    if (!string.IsNullOrWhiteSpace(str))
                    {
                        ban = new DbYangBan();
                        if (json["doType"].ToString() == "")
                        {
                            rsl.Message = "请选择样版状态";
                            return rsl;
                        }
                        ban.yStatus = json["doType"].ToString();
                        ban.yCode = str;
                        oper = new OperateModel();
                        oper.Data = ban;
                        oper.Conditions = "yCode";
                        oper.Types = OperateModel.OperateType.Edit;
                        operList.Add(oper);

                        #region 添加记录信息
                        DbBanGunRecords re = new DbBanGunRecords();
                        re.doType = json["doType"].ToString();
                        re.createtime = getNow();
                        re.dType = "YB";
                        re.pCode = str;
                        re.memo = json["memo"].ToString();
                        re.createuser = userLogin.UserInfo().userCode;
                        re.usCode = json["usersCode"].ToString();
                        oper = new OperateModel();
                        oper.Data = re;
                        oper.Types = OperateModel.OperateType.Add;
                        operList.Add(oper);
                        #endregion
                    }
                }
                if (operList.Count > 0)
                {
                    rsl = cmd.MoreUpdate(operList);
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取样版出入库记录信息
        /// </summary>
        /// <param name="yCode"></param>
        /// <returns></returns>
        public ReturnResult getYangBanRecords(string yCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from V_YangBanStatus_info where ");
                sb.Append("pCode='" + yCode + "'");
                var table = cmd.GetDataTable(sb.ToString());
                rsl.Result = true;
                rsl.Data = cmd.TableToDictionary(table);
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 检验版辊是否存在
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <returns></returns>
        public ReturnResult CheckProductBanGun(string proCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select pCode from fun_BanGun_info where proCode='"+ proCode +"'");
                sb.Append(" and isdel=0");
                var table = cmd.GetDataTable(sb.ToString());
                if (table.Rows.Count > 0)
                {
                    rsl.Message = "存在版辊：" + table.Rows[0]["pCode"].ToString();
                }
                else
                {
                    rsl.Result = true;
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
